# -*-coding:utf-8-*-
import os
import json
import time

import shutil
import urllib.request
import Setting
from PIL import Image, ImageDraw, ImageFont
from gzip import decompress



def getPollutionLevel(lev):
    lev = int(lev)

    if lev < 51:
        return '%s 优' % lev
    elif lev < 101:
        return '%s 良' % lev
    elif lev < 151:
        return '%s 轻度污染' % lev
    elif lev < 201:
        return '%s 中度污染' % lev
    elif lev < 301:
        return '%s 重度污染' % lev
    else:
        return '%s 严重污染' % lev

def getData():
    citycode = Setting.city
    keycode = Setting.key
    cityname = Setting.cityname

    # 设置请求地址与请求参数
    #request_url = 'http://d1.weather.com.cn/sk_2d/%s.html?_=%s' % (citycode, int(round(time.time() * 1000)))
    #request_url = 'http://www.weather.com.cn/data/sk/%s.html?_=%s' % (citycode, int(round(time.time() * 1000)))
    request_url = 'https://devapi.qweather.com/v7/air/now?location=%s&key=%s' % (citycode,keycode)
    request = urllib.request.Request(request_url)
    response = urllib.request.urlopen(request)

    # 读取请求结果并转换为JSON
    data = decompress(response.read())
    data = json.loads(data)['now']

    result = {}

    result['aqi'] = data['aqi']
    result['quality'] = data['category']


    request_url = 'https://devapi.qweather.com/v7/weather/now?location=%s&key=%s' % (citycode,keycode)
    request = urllib.request.Request(request_url)
    response = urllib.request.urlopen(request)

    # 读取请求结果并转换为JSON
    data = json.loads(decompress(response.read()))['now']

    result['city'] = cityname
    result['weather'] = data['text']
    result['temp'] = data['feelsLike']   #fl
    result['wind_power'] = data['windScale']
    result['wind_direction'] = data['windDir']
    result['wind_speed'] = data['windSpeed']
    result['wetness'] = data['humidity']

    date = time.strptime(data['obsTime'][0:15],'%Y-%m-%dT%H:%M')


    result['date'] = '%s月%s日(%s)' % (time.strftime('%m',date),time.strftime('%d',date),get_week_day(date))
    result['time'] = '%s:%s' % (time.strftime('%H',date) , time.strftime('%M',date))

    return result

def getWatermarkImage():
    # Configurations:
    textcolor = "#000000"

    fontPath = Setting.fontpath

    result = getData()

    # Build rich text for ads
    ad = []

    # Wrap line for text
    #   Special treated Chinese characters
    #   Workaround By Felix Yan - 20110508
    wraptext = [""]


    # Format wrapped lines to rich text
    wrap = [(text, textcolor) for text in wraptext]
    wrap += ad

    # Draw picture
    i = Image.new("RGBA", (290, 158), (255, 255, 255, 120))
    d = ImageDraw.Draw(i)
    # 输出城市信息
    d.text((20, 0), result['city'], font=ImageFont.truetype(fontPath, 72), fill=textcolor)
    # 输出温度信息
    d.text((len(result['city']) * 72 + 26, 72 - 48), ('%s℃' % result['temp']),
           font=ImageFont.truetype(fontPath, 48), fill=textcolor)
    # 添加分隔线
    d.line(((10, 82), (280, 82)), (0, 0, 0), width=3)
    # 添加天气和风力信息
    msg = "%(weather)s | %(wind_direction)s %(wind_power)s级 %(wind_speed)skm/h" % result
    d.text((20, 88), msg, font=ImageFont.truetype(fontPath, 20), fill=textcolor)
    # 添加湿度和空气质量信息
    msg = "湿度:%(wetness)s%% | %(aqi)s %(quality)s" % result
    d.text((20, 111), msg, font=ImageFont.truetype(fontPath, 20), fill=textcolor)
    # 添加一个灰色底色 用于衬托更新时间
    d.line(((0, 146), (290, 146)), (220, 220, 220, 220), width=24)

    # 输出更新时间信息
    d.text((20, 135), u'%s %s | 更新' % (result['date'],result['time']),
           font=ImageFont.truetype(fontPath, 17), fill="#000000")

    # Write result to a temp file
    filename = Setting.temppath+'/watermark.png'
    with open(filename, "wb") as s:
        i.save(s, "PNG")
    return filename

def returnSize(im):
    #返回图片大小,返回两个值,第一个返回值总为最大
    max,min = im.size
    if max > min:
        return max,min
    else:
        return min,max

def changeSize(wallpath):
    img = Image.open(wallpath)
    max,min = returnSize(img)
    value = min/Setting.resolution[1]
    max = max/value
    if max>Setting.resolution[0]:
        max=Setting.resolution[0]
    else:
        max=int(max)
    newimg = img.resize((max,Setting.resolution[1]),Image.Resampling.LANCZOS)
    newimg.save(wallpath)


def brand(wallpath, watermark):
    new_wallpath = wallpath[:wallpath.rfind('/')] + '/wallpaper%s' % wallpath[wallpath.rfind('.'):]
    shutil.copy(wallpath, new_wallpath)

    im = Image.open(new_wallpath)
    mark = Image.open(watermark)
    layer = Image.new('RGBA', im.size, (0, 0, 0, 0))
    layer.paste(mark, (im.size[0] - mark.size[0], mark.size[1]))
    out = Image.composite(layer, im, layer)
    out.save(new_wallpath)
    return new_wallpath

def get_week_day(date):
  week_day_dict = {
    0 : '星期一',
    1 : '星期二',
    2 : '星期三',
    3 : '星期四',
    4 : '星期五',
    5 : '星期六',
    6 : '星期天',
  }
  day = date.tm_wday
  return week_day_dict[day]
